//
//  UIViewController+AD.swift
//  ADKit
//
//  Created by Adoma on 2023/12/26.
//

import UIKit
import RxSwift

extension Reactive where Base: UIViewController {

    /// A presentViewController B 后，a.presentedViewController就是b，b.presentingViewController就是a
    /// by ADKit
    public var dismiss: Binder<Bool> {
        Binder(self.base) { O, animated in
            if let from = O.presentingViewController {
                from.dismiss(animated: animated)
            } else if let navi = O.navigationController {
                navi.popViewController(animated: animated)
            }
        }
    }
}

public extension UIViewController {
    
    /// by ADKit
    func rootDismiss(animated: Bool, completion: (()->Void)? = nil) {
        var root: UIViewController? = self
        while root?.presentingViewController != nil {
            root = root?.presentingViewController
        }
        root?.dismiss(animated: animated, completion: completion)
    }
    
    /// by ADKit
    func removeFromNavigation() {
        guard let navigationController = self.navigationController else { return }
        navigationController.viewControllers = navigationController.viewControllers.filter {
            $0 != self
        }
    }
    
    func popAllAfterSelf(animated: Bool) {
        guard let navigationController = self.navigationController else { return }
        guard let index = navigationController.viewControllers.firstIndex(of: self) else { return }
        
        let new = Array(navigationController.viewControllers.prefix(upTo: index))
        navigationController.setViewControllers(new, animated: animated)
    }
    
    func dismissOrPop(animated: Bool, completion: (()->Void)? = nil) {
        if let from = self.presentingViewController {
            from.dismiss(animated: animated, completion: completion)
        } else {
            if let navi = self.navigationController {
                navi.popViewController(animated: animated)
            }
            completion?()
        }
    }
    
    func dismissOrRemove(animated: Bool, completion: (()->Void)? = nil) {
        if let from = self.presentingViewController {
            from.dismiss(animated: animated, completion: completion)
        } else {
            removeFromNavigation()
            completion?()
        }
    }
}

